package com.hubiao.basics.thread.juc;

import java.util.concurrent.CountDownLatch;

/**
 * Description
 *
 * @author hubiao
 * @since 2021-01-27 16:33
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        //定义两个计数器
        CountDownLatch countDownLatch = new CountDownLatch( 2 );
        new Thread( new Runnable() {
            @Override
            public void run() {
                System.out.println( Thread.currentThread().getName() + ",子线程开始执行..." );
                //计数器值每次减去1
                countDownLatch.countDown();
                System.out.println( Thread.currentThread().getName() + ",子线程结束执行..." );
            }
        } ).start();
        new Thread( new Runnable() {
            @Override
            public void run() {
                System.out.println( Thread.currentThread().getName() + ",子线程开始执行..." );
                try {
                    Thread.sleep( 2000 );
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //计数器值每次减去1
                countDownLatch.countDown();
                System.out.println( Thread.currentThread().getName() + ",子线程结束执行..." );
            }
        } ).start();

        // 減去为0,线程才会恢复，任务继续执行
        countDownLatch.await();
        System.out.println( "两个子线程执行完毕...." );
        System.out.println( "主线程继续执行....." );
        for (int i = 0; i < 10; i++) {
            System.out.println( "main,i:" + i );
        }
    }

}
